<template>
  <div class="detail-container" v-loading="loading">
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
        <el-breadcrumb-item>景点详情</el-breadcrumb-item>
        <el-breadcrumb-item>{{ detail?.name || '-' }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="header">
      <div class="title-block">
        <h1 class="title">{{ detail?.name }}</h1>
        <div class="meta">
          <el-tag type="success" v-if="detail?.is_recommended">推荐</el-tag>
          <span class="location">
            <el-icon><Location /></el-icon>
            {{ detail?.province || '' }} {{ detail?.city || '' }} {{ detail?.district || '' }}
          </span>
          <span class="reviews">
            <el-rate v-model="detail.rating" disabled show-score text-color="#ff9900" score-template="{value}" />
            <span class="count">({{ detail?.review_count || 0 }})</span>
          </span>
        </div>
      </div>
      <div class="price-block">
        <div class="price" v-if="(detail?.price || 0) > 0">
          <span class="current">¥{{ detail?.price }}</span>
          <span class="original" v-if="detail?.original_price">¥{{ detail?.original_price }}</span>
        </div>
        <div class="price free" v-else>免费</div>
        <div class="actions">
          <el-button type="primary" :icon="ShoppingCart" @click="bookNow">立即预订</el-button>
          <el-button type="warning" plain @click="toggleFavorite">
            {{ isFavorite ? '取消收藏' : '收藏' }}
          </el-button>
        </div>
      </div>
    </div>

    <div class="gallery-and-info">
      <div class="gallery">
        <img :src="detail?.cover_image || 'https://picsum.photos/800/450'" alt="cover" />
      </div>
      <div class="info">
        <h3>简介</h3>
        <p class="desc">{{ detail?.description || '暂无介绍' }}</p>
        <div class="tags" v-if="detail?.tags">
          <el-tag v-for="t in (detail.tags || '').split(',')" :key="t" style="margin-right: 6px">{{ t }}</el-tag>
        </div>
        <div class="merchant" v-if="detail?.merchant_id">
          <el-button type="success" :icon="ChatRound" @click="contactMerchant">联系商家</el-button>
        </div>
      </div>
    </div>

    <div class="recommend-section" v-if="related.length">
      <div class="section-title">
        <h2>相关推荐</h2>
        <p>根据你的浏览与偏好推荐</p>
      </div>
      <div class="grid">
        <div v-for="item in related" :key="item.id" class="card" @click="goDetail(item.id)">
          <img :src="item.cover_image || 'https://picsum.photos/300/200'" />
          <div class="c-title">{{ item.name }}</div>
          <div class="c-meta">
            <span class="city">{{ item.city || item.province || '未知' }}</span>
            <span class="price" v-if="(item.price || 0) > 0">¥{{ item.price }}</span>
            <span class="free" v-else>免费</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Location, ShoppingCart, ChatRound } from '@element-plus/icons-vue'
import { travelAPI, recommendationAPI, profileAPI } from '../api/index.js'

const route = useRoute()
const router = useRouter()

const id = ref(Number.parseInt(route.params.id))
const loading = ref(false)
const detail = ref({})
const related = ref([])
const isFavorite = ref(false)

const loadDetail = async () => {
  loading.value = true
  try {
    const res = await travelAPI.getAttractionDetail(id.value)
    detail.value = res || {}
    // 检查是否收藏
    try {
      const favRes = await travelAPI.checkFavorite(id.value)
      isFavorite.value = !!favRes?.is_favorite
    } catch (_) {}
    // 相关推荐（登录用户）
    try {
      const token = localStorage.getItem('token')
      if (token) {
        const reco = await recommendationAPI.itemBased(6)
        related.value = reco?.attractions || []
      }
    } catch (e) {
      related.value = []
    }
  } catch (e) {
    ElMessage.error(e?.response?.data?.detail || '加载详情失败')
  } finally {
    loading.value = false
  }
}

const goDetail = (aid) => {
  router.push(`/attractions/${aid}`)
}

const bookNow = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push({ path: '/home', query: { book: id.value } })
}

const toggleFavorite = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  try {
    if (isFavorite.value) {
      await travelAPI.removeFavorite(id.value)
      isFavorite.value = false
      ElMessage.success('已取消收藏')
    } else {
      await travelAPI.addFavorite(id.value)
      isFavorite.value = true
      ElMessage.success('已收藏')
    }
  } catch (e) {
    ElMessage.error(e?.response?.data?.detail || '操作失败')
  }
}

const contactMerchant = () => {
  router.push('/chat')
}

onMounted(loadDetail)
watch(() => route.params.id, (nv) => {
  id.value = Number.parseInt(nv)
  loadDetail()
})
</script>

<style scoped>
.detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px 20px 40px;
}
.breadcrumb {
  margin: 10px 0 16px;
}
.header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 16px;
}
.title {
  margin: 0 0 8px;
  font-size: 24px;
  color: #333;
}
.meta {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #666;
}
.price-block {
  text-align: right;
  min-width: 240px;
}
.price .current {
  color: #ff6b6b;
  font-weight: 700;
  font-size: 22px;
  margin-right: 8px;
}
.price .original {
  color: #aaa;
  text-decoration: line-through;
}
.gallery-and-info {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}
.gallery img {
  width: 100%;
  height: 450px;
  object-fit: cover;
  border-radius: 10px;
}
.info {
  background: #fff;
  border-radius: 10px;
  padding: 16px;
}
.desc {
  color: #555;
  line-height: 1.7;
  white-space: pre-wrap;
}
.recommend-section {
  margin-top: 36px;
}
.section-title {
  text-align: center;
  margin-bottom: 16px;
}
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}
.card {
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: transform .2s ease;
}
.card:hover { transform: translateY(-3px); }
.card img {
  width: 100%;
  height: 140px;
  object-fit: cover;
}
.c-title {
  padding: 10px 12px 6px;
  font-weight: 600;
  color: #333;
}
.c-meta {
  padding: 0 12px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #666;
}
.free { color: #67c23a; font-weight: 600; }
</style>






